package com.dreamstations.changshads.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.dreamstations.changshads.R;
import com.dreamstations.changshads.activity.ArticleDetailActivity;
import com.dreamstations.changshads.activity.ArticleDetail_WebActivity;
import com.dreamstations.changshads.adapter.DSRvAdapter;
import com.dreamstations.changshads.entity.BaseBean;
import com.dreamstations.changshads.util.DSRequest;
import com.dreamstations.changshads.util.DSUtils;
import com.dreamstations.changshads.util.L;
import com.dreamstations.changshads.util.RequestType;
import com.squareup.picasso.Picasso;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.recyclerview.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

public class Home_Frag extends Fragment {
    private static final String TAG = Home_Frag.class.getName();
    private boolean isFirstIn = true;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private DSRvAdapter.RvSupport<BaseBean> item;

    private DSRvAdapter<BaseBean> adapter;
    private Picasso picasso;

    private int returned = 0;
    private int failed = 0;
    private List<BaseBean> fronts;
    private int retryTime = 0;

    private DSRequest.DSCallback<List<BaseBean>> dsCallback;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        picasso = Picasso.with(getActivity());
        fronts = new ArrayList<>();
        dsCallback = new DSRequest.DSCallback<List<BaseBean>>() {
            @Override
            public void onResponse(List<BaseBean> result) {
                returned++;       //通知累加器返回了值
                if (result.size() == 0) {
                    L.i(TAG, "=>loadData:error," + "返回的值为空");
                    return;
                }
                L.i(TAG, "=>loadData:" + String.valueOf(returned));
                fronts.add(result.get(0));
                if (returned < 8) {  //还没加载完
                    return;


                }        //所有的值已经被加载
                if (failed < 6) {
                    assertSuccess();
                } else {
                    assertFailed();
                }
            }

            @Override
            public void onFailure(String msg) {
                returned++;       //通知累加器返回了值
                L.w(TAG, "=>loadData:error:" + msg + ",tryAgain:" + retryTime);
                failed++;           //又失败一个
                if (returned < 8) return;
                if (failed < 6) {  //所有的请求都返回了
                    assertSuccess();
                } else {
                    assertFailed();
                }
            }
        };
    }

    /**
     * 断言请求失败
     * 1、重新尝试次数自增
     * 2、通知进度圈加载完成
     * 3、发起一轮请求
     */
    private void assertFailed() {
        retryTime++;
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (retryTime > 5) {
            L.w(TAG, "=>over retrytime");
            Toast.makeText(getActivity(), "无法取得最新数据，请稍后重试", Toast.LENGTH_SHORT).show();
            return;
        }

        L.d(TAG, "=>assertFailed");
        loadData(1, DSUtils.NETWORK_ELSE_CACHED);
    }

    /**
     * 断言请求成功
     * 1、重置重新尝试次数
     * 2、通知进度圈加载完成
     * 3、绑定数据
     * 4、若是第一次进入，则尝试获取最新数据
     */
    private void assertSuccess() {
        L.d(TAG, "=>assertSuccess");
        retryTime = 0;
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (adapter == null) return;
        adapter.setItemDatas(fronts);
        if (isFirstIn) {
            isFirstIn = false;
            loadData(1, DSUtils.NETWORK_ELSE_CACHED);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        swipeRefreshLayout = (SwipeRefreshLayout) inflater.inflate(R.layout.simple_refreshable, container, false);
        recyclerView = (RecyclerView) swipeRefreshLayout.getChildAt(1);

        initView();

        int cacheType = DSUtils.NETWORK_ELSE_CACHED;
        if (isFirstIn) cacheType = DSUtils.ONLY_CACHED;
        loadData(1, cacheType);

        return swipeRefreshLayout;
    }

    /**
     * 1、取消当前正在进行的请求
     * 2、重置已返回和失败的请求计数器
     * 3、清空保存的list
     * 4、发起新的请求
     *
     * @param page
     * @param cacheType
     */
    private void loadData(int page, int cacheType) {
        swipeRefreshLayout.setRefreshing(true);
        returned = 0;
        failed = 0;
        DSUtils.getInstance().cancelByTag(Home_Frag.this);
        returned = 0;
        failed = 0;
        fronts.clear();
        new DSRequest()
                .type(RequestType.TYPE_WORK)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .addParams("front", "1")
                .cacheType(cacheType)
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
        new DSRequest()
                .type(RequestType.TYPE_INVESTIGATE)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .cacheType(cacheType)
                .addParams("front", "1")
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
        new DSRequest()
                .type(RequestType.TYPE_TOPIC)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .cacheType(cacheType)
                .addParams("front", "1")
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
        new DSRequest()
                .type(RequestType.TYPE_DATUM_LITERATURE)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .addParams("front", "1")
                .cacheType(cacheType)
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
        new DSRequest()
                .type(RequestType.TYPE_FIGURE)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .addParams("front", "1")
                .cacheType(cacheType)
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
        new DSRequest()
                .type(RequestType.TYPE_STORY)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .addParams("front", "1")
                .cacheType(cacheType)
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
        new DSRequest()
                .type(RequestType.TYPE_RESOURCE)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .addParams("front", "1")
                .cacheType(cacheType)
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
        new DSRequest()
                .type(RequestType.TYPE_LIBRARY)
                .addParams("page", "1")
                .addParams("typeId", "1")
                .addParams("front", "1")
                .cacheType(cacheType)
                .setTag(Home_Frag.this)
                .build()
                .execute(dsCallback);
    }

    private void initView() {
        //设置布局管理器
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        //设置item间隔
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, 0, 0, 16);
            }
        });

        item = new DSRvAdapter.RvSupport<BaseBean>() {
            @Override
            public int getItemViewType(BaseBean data) {
                return 0;
            }

            @Override
            public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {
                return ViewHolder.get(context, null, parent, R.layout.home_item, -1);
            }

            @Override
            public void convert(ViewHolder holder, BaseBean data) {
                ImageView iv = holder.getView(R.id.home_item_img);
                L.i(TAG, "=>loadImg:" + DSRequest.SERVER_BASE1 + data.getCover());
                picasso.load(DSRequest.SERVER_BASE1 + data.getCover())
                        .tag(getContext())
                        .placeholder(R.drawable.img_default)
                        .into(iv);
                holder.setText(R.id.title, data.getTitle());
            }
        };

        adapter = new DSRvAdapter<>(getContext(), new ArrayList<BaseBean>()
                , item);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener<BaseBean>() {
            @Override
            public void onItemClick(ViewGroup parent, View view, BaseBean o, int position) {
                Intent intent = new Intent();
                if (o.getTemplate() == 2) {
                    intent.setClass(getActivity(), ArticleDetailActivity.class);
                } else {
                    intent.setClass(getActivity(), ArticleDetail_WebActivity.class);
                }
                intent.putExtra("data", o);
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(ViewGroup parent, View view, BaseBean o, int position) {
                return false;
            }
        });

//        设置刷新监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                L.i(TAG, "=>onRefresh");
                loadData(1, DSUtils.NETWORK_ELSE_CACHED);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        int cacheType = DSUtils.NETWORK_ELSE_CACHED;
//        if (isFirstIn) cacheType = DSUtils.ONLY_CACHED;
//        loadData(1, cacheType);
    }

    @Override
    public void onPause() {
        L.i(TAG, "=>onPause:");
        DSUtils.getInstance().cancelByTag(Home_Frag.this);
        swipeRefreshLayout.setRefreshing(false);
        super.onPause();
    }
}
